<!-- 个人信息页面 -->
<template>
  <div id="test4">
    <el-card style="overflow: hidden;">
      <el-card style="float: left;" class="box-card sb">
        <template #header>
          <div class="card-header">
            <span>头像设置</span>
          </div>
        </template>
        <div style="display: flex">
          <input
            ref="input"
            type="file"
            name="image"
            accept="image/*"
            @change="setImage"
          />

          <div class="content">
            <section class="cropper-area">
              <div class="img-cropper">
                <vue-cropper
                  ref="cropper"
                  :aspect-ratio="16 / 9"
                  :src="user.picture"
                  preview=".preview"
                />
              </div>
              <div class="actions">
                <a href="#" role="button" @click.prevent="showFileChooser">
                  选择图片
                </a>
                <a href="#" role="button" @click.prevent="rotate(90)">
                  ↻ 右转
                </a>
                <a href="#" role="button" @click.prevent="rotate(-90)">
                  ↺ 左转
                </a>
                <el-button size="mini" type="success" @click="uploadImg('blob')"
                  >上传封面
                  <el-icon><UploadFilled /></el-icon>
                </el-button>
              </div>
            </section>
          </div>
          <!-- <section class="preview-area">
        <p>Preview</p>
        <div class="preview" />
        <p>Cropped Image</p>
        <div class="cropped-image">
          <img
            v-if="cropImg"
            :src="cropImg"
            alt="Cropped Image"
          />
          <div v-else class="crop-placeholder" />
        </div>
      </section> -->
        </div>
      </el-card>
      <el-card style="float: right;" class="box-card sb">
        <template #header>
          <div class="card-header">
            <span>账号编辑</span>
          </div>
        </template>
        <div>
    <el-form :model="ruleForm" :rules="rules" label-width="120px">
        <el-form-item label="修改用户名" prop="username">
            <el-input v-model="ruleForm.username" suffix-icon="UserFilled"/>
        </el-form-item>
        <el-form-item label="修改密码" prop="password">
            <el-input v-model="ruleForm.password" suffix-icon="Edit"/>
        </el-form-item>
        <el-form-item label="再次输入密码" prop="passagain">
            <el-input v-model="ruleForm.passagain" suffix-icon="Edit"/>
        </el-form-item>
        <el-form-item>
            <el-button type="success" icon="Check" @click="regist()">
                保存
            </el-button>
        </el-form-item>
    </el-form>
  </div>
      </el-card>
    </el-card>
  </div>
</template>

<script>
import VueCropper from "vue-cropperjs";
import "cropperjs/dist/cropper.css";
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { computed } from "vue";
import { mapState } from "vuex";

export default {
  name: "Test4",
  components: {
    VueCropper,
  },
  computed:{
    ...mapState({
      user:state=>state.user,
      ruleForm:state=>state.user
    }),
    // user(){
    //   return this.$store.state.user
    // }
  },
  props: {

  },
  data() {
    return {
      cropImg: "",
      data: null,
      ruleForm:{
            username:'',
            password:'',
            passagain:''
        },
        rules:{
            username:[
                {required: true, message:'输入用户名不能为空', trigger: 'blur'},
                {pattern:/^\w{3,5}$/, message:'用户名长度为3-5位', trigger: 'change'},
                {asyncValidator:(rule,value)=>{
                    return new Promise((resolve,reject)=>{
                        axios.get("http://localhost:8888/isexistExcludingMe",{
                          params:{
                            strname:this.ruleForm.username,
                            u_id:this.$store.state.user.u_id
                          }
                        }).then((res)=>{
                          if(res.data){
                              reject('用户名已存在')
                          }else{
                              resolve()
                          }
                      })
                    })
                },trigger:'blur'}
            ],
            password:[
                {required: true, message:'输入密码不能为空', trigger: 'blur'},
                {pattern:/^\w{5-16}$/, message:'密码长度为5-16位', trigger: 'change'},
            ],
            passagain:[
                {required: true, message:'再次输入密码不能为空', trigger: 'blur'},
                {validator:(rule,value)=>{
                    return value == this.ruleForm.password
                }, message:'两次输入密码不一致', trigger: 'change'},
            ]
        }
    };
  },
  methods: {
    regist(){
        if(this.ruleForm.username != '' && this.ruleForm.password != ''){
          axios.get("http://localhost:8888/user/changeUserInfo",{
            params:{
              username:this.ruleForm.username,
              password:this.ruleForm.password,
              u_id:this.$store.state.user.u_id
          }}).then((data)=>{
              if(data.data.data){
                ElMessage({
                  message: '修改成功.',
                  type: 'success',
                })
                this.ruleForm.password=''
                this.ruleForm.passagain=''
              }
          })
        }else{
            alert("请勿为空")
        }
    },
    uploadImg() {
      // 调用组件实例的方法
      this.cropImage();
      console.log(this.cropImg);

      const formData = new FormData();
      formData.append('img', this.cropImg);
      const url = 'http://localhost:8888/gravatar/gravatarUpload'
      axios.post(url, formData,{header:{'Content-Type': 'multipart/form-data','Cache-Control': 'no-cache'}}).then( data =>{
        ElMessage({
          message: '头像上传成功.',
          type: 'success',
        })
        //更新头像,在更新头像后组件的:src属性会自己重新请求后台加载图片数据
        this.user.picture = data.data.data[0].url;
        //报存更改的头像到数据库
        axios.get("http://localhost:8888/user/changeUserGravatar",{
            params:{
              picture:this.user.picture,
              u_id:this.$store.state.user.u_id
            }
          }).then((data)=>{
            if(data.data.data){
              ElMessage({
                message: '头像修改成功.',
                type: 'success',
              })
            }
          })
        console.log(this.user.picture);
      }).catch(Response=>{
        ElMessage.error('上传失败.')
        console.error(Response);
      })
    },
    cropImage() {
      // get image data for post processing, e.g. upload or setting image src
      this.cropImg = this.$refs.cropper.getCroppedCanvas().toDataURL();
    },
    flipX() {
      const dom = this.$refs.flipX;
      let scale = dom.getAttribute("data-scale");
      scale = scale ? -scale : -1;
      this.$refs.cropper.scaleX(scale);
      dom.setAttribute("data-scale", scale);
    },
    flipY() {
      const dom = this.$refs.flipY;
      let scale = dom.getAttribute("data-scale");
      scale = scale ? -scale : -1;
      this.$refs.cropper.scaleY(scale);
      dom.setAttribute("data-scale", scale);
    },
    getCropBoxData() {
      this.data = JSON.stringify(this.$refs.cropper.getCropBoxData(), null, 4);
    },
    getData() {
      this.data = JSON.stringify(this.$refs.cropper.getData(), null, 4);
    },
    move(offsetX, offsetY) {
      this.$refs.cropper.move(offsetX, offsetY);
    },
    reset() {
      this.$refs.cropper.reset();
    },
    rotate(deg) {
      this.$refs.cropper.rotate(deg);
    },
    setCropBoxData() {
      if (!this.data) return;

      this.$refs.cropper.setCropBoxData(JSON.parse(this.data));
    },
    setData() {
      if (!this.data) return;

      this.$refs.cropper.setData(JSON.parse(this.data));
    },
    setImage(e) {
      const file = e.target.files[0];

      if (file.type.indexOf("image/") === -1) {
        alert("Please select an image file");
        return;
      }

      if (typeof FileReader === "function") {
        const reader = new FileReader();

        reader.onload = (event) => {
          this.imgSrc = event.target.result;
          // rebuild cropperjs with the updated source
          this.$refs.cropper.replace(event.target.result);
        };

        reader.readAsDataURL(file);
      } else {
        alert("Sorry, FileReader API not supported");
      }
    },
    showFileChooser() {
      this.$refs.input.click();
    },
    zoom(percent) {
      this.$refs.cropper.relativeZoom(percent);
    }
  },
  created() {
     this.ruleForm = this.$store.state.user

    // const formData = new FormData();
    //   formData.append('flag', '809ab9c0928d4184b69b69285dd28d3b');
    //   const url = 'http://localhost:8888/gravatar/809ab9c0928d4184b69b69285dd28d3b'
    //   axios.post(url).then( data =>{
    //     ElMessage({
    //       message: '获取成功.',
    //       type: 'success',
    //     })
    //     console.log(data);
    //   }).catch(Response=>{
    //     ElMessage.error('获取失败.')
    //   })
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
input[type="file"] {
  display: none;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0 5px 0;
}

.header h2 {
  margin: 0;
}

.header a {
  text-decoration: none;
  color: black;
}

.content {
  display: flex;
  justify-content: space-between;
  width: 450px;
}

.cropper-area {
  width: 614px;
}

.actions {
  margin-top: 1rem;
}

.actions a {
  display: inline-block;
  padding: 5px 15px;
  background: #0062cc;
  color: white;
  text-decoration: none;
  border-radius: 3px;
  margin-right: 1rem;
  margin-bottom: 1rem;
}

textarea {
  width: 100px;
  height: 100px;
}

.preview-area {
  width: 307px;
}

.preview-area p {
  font-size: 1.25rem;
  margin: 0;
  margin-bottom: 1rem;
}

.preview-area p:last-of-type {
  margin-top: 1rem;
}

.preview {
  width: 100%;
  height: calc(372px * (9 / 16));
  overflow: hidden;
  border-radius: 100%;
}

.crop-placeholder {
  width: 100%;
  height: 200px;
  background: #ccc;
}

.cropped-image img {
  max-width: 100%;
}

.sb{
  width: 49%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
